package cn.zyjblogs.config.security.policy;

import cn.zyjblogs.starter.common.entity.constant.CommonRedisKeyConstant;
import cn.zyjblogs.starter.redis.utils.RedisTemplateHandler;
import lombok.SneakyThrows;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.util.RandomValueStringGenerator;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;

import java.util.concurrent.TimeUnit;

/**
 * @author zhuyijun
 */
public class OauthAuthorizationCodeServices implements AuthorizationCodeServices {
    private final RedisTemplateHandler<String, OAuth2Authentication> redisTemplateHandler;

    public OauthAuthorizationCodeServices(RedisTemplateHandler redisTemplateHandler) {
        this.redisTemplateHandler = redisTemplateHandler;
    }

    /**
     * 生成随机字符的类
     */
    private RandomValueStringGenerator generator = new RandomValueStringGenerator(16);

    /**
     * @description 生成授权码的方法
     * @param: [oAuth2Authentication]
     * @return: java.lang.String
     */
    @SneakyThrows
    @Override
    public String createAuthorizationCode(OAuth2Authentication oAuth2Authentication) {
        String code = this.generator.generate();
        redisTemplateHandler.set(CommonRedisKeyConstant.AUTHORIZATION_CODE + ":" + code, oAuth2Authentication);
        redisTemplateHandler.expire(CommonRedisKeyConstant.AUTHORIZATION_CODE + ":" + code, 1, TimeUnit.MINUTES);
//        redisTemplateHandler.hPut(CommonRedisKeyConstant.AUTHORIZATION_CODE, code, oAuth2Authentication);
        return code;
    }

    /**
     * @description
     * @param: [code]
     * @return: org.springframework.security.oauth2.provider.OAuth2Authentication
     */
    @SneakyThrows
    @Override
    public OAuth2Authentication consumeAuthorizationCode(String code) throws InvalidGrantException {
//        OAuth2Authentication oAuth2Authentication = redisTemplateHandler.<String, OAuth2Authentication>hGet(CommonRedisKeyConstant.AUTHORIZATION_CODE, code);
//        redisTemplateHandler.hDelete(CommonRedisKeyConstant.AUTHORIZATION_CODE, code);
        OAuth2Authentication oAuth2Authentication = redisTemplateHandler.get(CommonRedisKeyConstant.AUTHORIZATION_CODE + ":" + code);
        redisTemplateHandler.delete(CommonRedisKeyConstant.AUTHORIZATION_CODE + ":" + code);
        return oAuth2Authentication;
    }


}
